<script setup lang="ts">
//
import type { XtxGuessInstance } from '@/types/components'
import CustomNavbar from './componets/CustomNavbar.vue'
import { onLoad } from '@dcloudio/uni-app'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './componets/CategoryPanel.vue'
import HotPanel from './componets/HotPanel.vue'
import PageSkeleton from './componets/PageSkeleton.vue'
const bannerlist = ref<BannerItem[]>([])

// 获取前台轮播图数据
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerlist.value = res.result
}
// 获取前台分类数据
const categoryList = ref<CategoryItem>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

//
const hotList = ref<HotItem>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

// 页面加载
// 是否加载中标记
const isLoading = ref(false)
onLoad(async () => {
  // 开始加载
  isLoading.value = true
  // 加载完毕
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

//
// 获取猜你喜欢组件实例
const guessRef = ref<XtxGuessInstance>()

// 滚动触底事件
const onScrolltolower = () => {
  guessRef.value?.getMore()
}
// 下拉刷新
const isTriggered = ref(false)

const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 重新获取数据
  // 重置猜你喜欢的数据
  // 重新获取数据
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.resetData(),
  ])
  // 关闭动画
  isTriggered.value = false
  // 重置页码，重置列表，重置结束标记
}
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <scroll-view
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    refresher-enabled
    class="scroll_v view"
    scroll-y
    @scrolltolower="onScrolltolower"
  >
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading" />
    <!-- 自定义轮播图 -->
    <XtxSwiper :list="bannerlist" />
    <!-- 分类面板 -->
    <CategoryPanel :list="categoryList"></CategoryPanel>
    <!-- 热门推荐 -->
    <HotPanel :list="hotList" />
    <!-- 猜你喜欢的组件 -->
    <XtxGuess ref="guessRef"></XtxGuess>
  </scroll-view>
</template>

<style lang="scss">
//
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll_view {
  flex: 1;
}
</style>
